package com.way.capture.utils;

import android.os.Looper;
import androidx.annotation.CheckResult;
import androidx.annotation.NonNull;
import android.view.View;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.MainThreadDisposable;
import io.reactivex.disposables.Disposables;

public class RxView extends Observable<View> {
    private final View view;

    RxView(View view) {
        this.view = view;
    }

    public static void checkNotNull(Object value, String message) {
        if (value == null) {
            throw new NullPointerException(message);
        }
    }

    public static boolean checkMainThread(Observer<?> observer) {
        if (Looper.myLooper() != Looper.getMainLooper()) {
            observer.onSubscribe(Disposables.empty());
            observer.onError(new IllegalStateException(
                    "Expected to be called on the main thread but was " + Thread.currentThread().getName()));
            return false;
        }
        return true;
    }

    @CheckResult
    @NonNull
    public static Observable<View> clicks(@NonNull View view) {
        checkNotNull(view, "view == null");
        return new RxView(view);
    }

    @Override
    protected void subscribeActual(Observer<? super View> observer) {
        if (!checkMainThread(observer)) {
            return;
        }
        RxView.Listener listener = new RxView.Listener(view, observer);
        observer.onSubscribe(listener);
        view.setOnClickListener(listener);
    }

    static final class Listener extends MainThreadDisposable implements View.OnClickListener {
        private final View view;
        private final Observer<? super View> observer;

        Listener(View view, Observer<? super View> observer) {
            this.view = view;
            this.observer = observer;
        }

        @Override
        public void onClick(View v) {
            if (!isDisposed()) {
                observer.onNext(v);
            }
        }

        @Override
        protected void onDispose() {
            view.setOnClickListener(null);
        }
    }
}
